package com.example.lettcode._202408._20240830;

import java.util.Arrays;

/**
 * 移除指定元素
 */
public class RemoveElement {

    public static void main(String[] args) {
        int[] nums = {3, 2, 2, 3,4,5,2,7,3,3,8,9};
        int val = 3;

        int i = removeElement4(nums, val);
        Arrays.stream(nums).forEach(System.out::print);
        System.out.println();
        System.out.println(i);
    }

    public static int removeElement(int[] nums, int val) {
        int m = nums.length;
        int count = 1;
        int tmp;
        for (int i = 0, j = 0; i < nums.length; i++) {
            if (nums[j] == val) {
                m--;
                tmp = nums[j];
                while ( nums[j] == nums[nums.length -count] && count + j < nums.length) {
                    count++;
                    m--;
                }
                nums[j] = nums[nums.length -count];
                nums[nums.length-count] = tmp;
                count++;
                i++;
            }
            j++;
        }
        return m;
    }

    public static int removeElement2(int[] nums, int val) {
        int m = nums.length;
        int count = 0;
        int tmp;
        for (int i = nums.length-1, j = nums.length-1; i > 0 ; i--) {
            if (nums[j] == val) {
                m--;
                tmp = nums[j];
                while ( nums[j] == nums[count] && count + j < nums.length) {
                    count++;
                    m--;
                }
                nums[j] = nums[count];
                nums[count] = tmp;
                count++;
                i--;
            }
            j--;
        }
        return m;
    }

    public static int removeElement3(int[] nums, int val) {
        int n = nums.length;
        int left = 0;
        for (int right = 0; right < n; right++) {
            if (nums[right] != val) {
                nums[left] = nums[right];
                left++;
            }
        }
        return left;
    }

    public static int removeElement4(int[] nums, int val) {
        int left = 0;
        int right = 0;
        for (right = 0; right < nums.length; right++) {
            if (nums[right] != val) {
                nums[left] = nums[right];
                left++;
            }
        }
        return left;
    }

}
